package org.example.shop.service;

import org.example.shop.dao.GoodsDao;
import org.example.shop.dao.OrderDao;
import org.example.shop.pojo.Goods;
import org.example.shop.pojo.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class GoodsServiceImpl implements GoodsService {
    private GoodsDao goodsDao;
    private OrderDao orderDao;

    @Autowired
    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    @Autowired
    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    public List<Goods> findAll(){
        return goodsDao.findAll();
    }

    @Override
    @Transactional // 启用事务
    public Integer secKill(Integer gid, int count) {
        // 使用jpa查询商品信息
        Optional<Goods> goodsOptional = goodsDao.findById(gid);
        // 判断商品是否存在
        if (!goodsOptional.isPresent()) {
            throw new RuntimeException("秒杀的商品不存在");
        }
        Goods goods = goodsOptional.get();
        // 判断库存是否小于购买数量
        if (goods.getStock() < count) {
            throw new RuntimeException("商品库存不足1");
        }

        // 创建订单
        Orders o = new Orders();
        o.setGid(gid).setPrice(goods.getPrice()).setCount(count);
        // 保存订单数据
        orderDao.save(o);
        // 可能有问题？
//        goods.setStock(goods.getStock() - count); // 重新设置库存 -- 没有锁 所以抛弃
//        goodsDao.save(goods); // 更新商品库存
        // 直接在mysql中减
        // update goods set stock = stock - 数量 where id=编号
        // 执行减库存 并获取受影响行数
        int resultCount = goodsDao.deductCount(gid, count); // 直接在数据库的基础上 进行库存减少
        // 只有库存不够 才不会真正执行更新操作 所以受影响为0
        if (resultCount < 1) {
            throw new RuntimeException("商品库存不足2 => " + resultCount);
        }
        return o.getId();
    }
}
